﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http;
using Microsoft.Extensions.Logging;
using System.Diagnostics;
using Microsoft.AspNet.Routing;

namespace Sino.CapacityCloud.Infrastructure.Midwares
{

    public class RequestLoggerMiddleware
    {

        private readonly RequestDelegate _next;
        private readonly ILogger _logger;

        private readonly string logTemplate;

        public RequestLoggerMiddleware(RequestDelegate next, ILoggerFactory loggerFactory)
        {
            _next = next;
            _logger = loggerFactory.CreateLogger<RequestLoggerMiddleware>();
            logTemplate = string.Join(Environment.NewLine, @"Client IP: {clientIP}
                                Request path: {requestPath}
                                Request content type: {requestContentType}
                                Request content length: {requestContentLength}
                                Start time: {startTime}
                                Duration: {duration}".Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim()));
        }

        public async Task Invoke(HttpContext context)
        {
            var startTime = DateTime.UtcNow;

            var watch = Stopwatch.StartNew();
            await _next.Invoke(context);
            watch.Stop();

            _logger.LogInformation(logTemplate,
                context.Connection.RemoteIpAddress?.ToString(),
                context.Request.Path,
                context.Request.ContentType,
                context.Request.ContentLength,
                startTime,
                watch.ElapsedMilliseconds);
        }

    }

    public static class RequestLoggerMiddlewareExtensions
    {

        public static IApplicationBuilder UseRequestLoggerMiddleware(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<RequestLoggerMiddleware>();
        }

    }

}